/*
 * Copyright (c) 2023, 2023,yzc.cn All rights reserved.
 *
 */
package cn.yzc.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Base64;

/**
 * <p>Project: SpringColud - AuthInterceptor</p>
 * <p>Powered by yzc On 2023-12-29 17:36:18</p>
 * <p>描述：<p>
 *
 * @author yzc [yzc0415@126.com]
 * @version 1.0
 * @since 17
 */

public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String auto = request.getHeader("Authorization");
        if( null == auto){
            //没有传递认证信息
            respJson(response,"没有认证信息");
            return false;
        }
        //不为空 Basic xxxxxx
        String[] info = auto.split("\\s+");
        if (info.length != 2){
            respJson(response,"没有认证信息");
            return false;
        }
        //获得 账号*****
        String tmp = info[1];
        //解密 username:password
        String decode = new String(Base64.getDecoder().decode(tmp));

        //继续分割
        String[] gdt = decode.split(":");
        String username = gdt[0];
        String password = gdt[1];

        if("admin".equals(username) && "123456".equals(password))
            return true;
        respJson(response,"用户名密码不正确");
        return false;
    }

    void respJson(HttpServletResponse response,String msg) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter pw = response.getWriter();
        pw.write("{\"code\":0,\"msg\":\""+msg+"\"}");
    }
}
